use std::{collections::HashMap, fs::File, io::copy, path::Path, str::FromStr};

use reqwest::{blocking::{Client, Response}, header::{HeaderMap, HeaderName, HeaderValue, USER_AGENT}, StatusCode};

use super::error::{WError, WResult};




fn download_inner(url: &str, headers: Option<&HashMap<String, String>>) -> WResult<Response> {
    let mut headers_now = HeaderMap::new();
    headers_now.insert(USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.33".parse().unwrap());
    if let Some(headers) = headers {
        headers_now.extend(headers.iter().map(| (k, v) | {
            (HeaderName::from_str(k.as_str()).unwrap(), HeaderValue::from_str(v.as_str()).unwrap())
        }));
    }

    let res = Client::builder()
        .build()?
        .get(url)
        .headers(headers_now)
        .send()?;

    if res.status() != StatusCode::OK {
        return Err(WError::NetError(format!("{}", res.status())));
    }

    Ok(res)
}


pub fn download_txt(url: &str, headers: Option<&HashMap<String, String>>) -> WResult<String> {
    let response = download_inner(url, headers)?;
    let res = response.text()?.trim().to_owned();
    Ok(res)
}

pub fn download_file(url: &str, headers: Option<&HashMap<String, String>>, p: &Path) -> WResult<()> {
    let mut response = download_inner(url, headers)?;
    let mut f = File::create(p)?;
    copy(&mut response, &mut f)?;
    Ok(())
}